package JdbcTest.Homework.books.dao.Impl;

import JdbcTest.Homework.books.dao.BookDao;
import JdbcTest.Homework.books.pojo.Books;
import JdbcTest.Homework.books.utils.JdbcUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class BookDaoImpl implements BookDao {
    ArrayList<Books> bookList = new ArrayList<>();
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    //查询所以图书信息
    @Override
    public ArrayList<Books> select() {
        try {
            conn = JdbcUtils.getConnection();
            String sql = "select * from books";
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                int id = rs.getInt("bookId");
                String bookName = rs.getString("bookName");
                int count = rs.getInt("bookCounts");
                String detail = rs.getString("dateil");
                Books books = new Books(id,bookName,count,detail);
                bookList.add(books);
            }
            return bookList;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            JdbcUtils.close(null,ps,rs);
        }
        return null;
    }

    @Override
    public boolean update(Books books) {
        try {
            if(conn == null){
                conn = JdbcUtils.getConnection();
            }
            String sql = "update books set bookCounts = ? where bookId = ?";
            ps = conn.prepareStatement(sql);
            ps.setInt(1,books.getbCount());
            ps.setInt(2,books.getbId());
            int num = ps.executeUpdate();
            return num == 1?true:false;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.close(null,ps);
        }
        return false;
    }
}
